<?php
/***********************************************************
 * 后台管理
 * @作者 pcfcms <1131680521@qq.com>
 * @主页 http://www.pcfcms.com
 * @时间 2021年01月01日
***********************************************************/
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
class Index extends Base
{

    public function index()
    {
        //后台模块导航
        $getMenu = Cache::get('getMenuglobal');
        if(empty($getMenu)){
           $getMenu = Db::name('menu')
                    ->where(['parent_id' => 0,'is_show' => 1,'status'=>1])
                    ->order('sort asc')
                    ->select()->toArray();
            foreach ($getMenu as $key => $value) {
                $getMenu[$key]['param'] = '/'.$value['param'];
            }
            Cache::tag('getmenu_cache')->set('getMenuglobal', $getMenu, ADMIN_CACHE_TIME);
        }
        $this->assign('getMenu',$getMenu);
        $this->assign('leftmenu',getMenuList());//后台左侧导航
        $this->assign('pcfadmin_info', getAdminInfo(session::get('admin_id')));//登录后台显示账号
        
        //主题 
        if(empty(PUBLIC_ROOT)){
          $this->assign('theme_url', Request::domain());
        }else{
          $this->assign('theme_url', Request::domain().'/'.PUBLIC_ROOT.'/');  
        }
        
        return $this->fetch();
    }

    // 系统首页
    public function main()
    {
        // 服务器信息
        $this->assign('sys_info',$this->get_sys_info());
        // 升级弹窗
        $this->assign('web_show_popup_upgrade', sysConfig('web.web_show_popup_upgrade'));
        // 纠正上传附件的大小，始终以空间大小为准
        $file_size = !empty(sysConfig('global.file_size'))?sysConfig('global.file_size'):'';
        $maxFileupload = @ini_get('file_uploads') ? ini_get('upload_max_filesize'):0;
        $maxFileupload = intval($maxFileupload);
        if (empty($file_size) || $file_size > $maxFileupload) {
            sysConfig('basic', ['file_size'=>$maxFileupload]);
        }
        // 快捷导航
        $quickMenu = Db::name('quickentry')->where(['checked' => 1,'status' => 1])->order('sort_order asc, id asc')->select()->toArray();
        $this->assign('quickMenu',$quickMenu);
        // 最近登录
        if(Session::get('admin_id') != 1 && Session::get('admin_info.role_id') > 0){
            $adminlog = Db::name('admin_log')
                      ->field('log_info,log_ip,log_time,admin_id')
                      ->where('admin_id',Session::get('admin_id'))
                      ->limit(11)
                      ->order('log_id desc')
                      ->select()->toArray();
        }else{
            $adminlog = Db::name('admin_log')
                      ->field('log_info,log_ip,log_time,admin_id')
                      ->limit(11)
                      ->order('log_id desc')
                      ->select()->toArray();
        }
        foreach ($adminlog as $key => $value) {
            $adminlog[$key]['log_time'] = pcftime($value['log_time']);
            $adminlog[$key]['adminname'] = Db::name('admin')->where('admin_id', $value['admin_id'])->value('user_name');
            unset($adminlog[$key]['admin_id']);
        }
        $this->assign('adminlog',$adminlog);
        return $this->fetch();
    }

    // 快捷导航管理
    public function ajax_quickmenu()
    {
        $domain = Request::baseFile().'/index/main';
        if (Request::isAjax()) {
            $checkedids = input('post.checkedids/a', []);
            $ids = input('post.ids/a', []);
            $saveData = [];
            foreach ($ids as $key => $val) {
                if (in_array($val, $checkedids)) {
                    $checked = 1;
                } else {
                    $checked = 0;
                }
                $saveData[$key] = [
                    'id'            => $val,
                    'checked'       => $checked,
                    'sort_order'    => intval($key) + 1,
                    'update_time'   => getTime(),
                ];
            }
            if (!empty($saveData)) {
                foreach ($saveData as $key => $value) {
                    Db::name('quickentry')->where('id', $value['id'])->update($value);
                }
                $result = ['status' => true,'msg' => '操作成功','url'=>$domain];
                return $result;
            }
            $result = ['status' => false,'msg' => '操作失败'];
            return $result;
        }
        $menuList = Db::name('quickentry')->where(['groups'=> 0,'status'=> 1])->order('sort_order asc, id asc')->select()->toArray();
        $this->assign('menuList',$menuList);
        return $this->fetch('quickmenu');
    }

    // 清除整站全部缓存
    public function clearCache()
    {

        if (!function_exists('unlink')) {
            $result = ['status' => 0, 'msg' => 'php.ini未开启unlink函数，请联系空间商处理！','url'=>''];
            return json($result);
        }
        // 兼容每个用户的自定义字段，重新生成数据表字段缓存文件
        $systemTables = ['arctype'];
        $data = Db::name('channel_type')->column('table');
        $tables = array_merge($systemTables, $data);
        foreach ($tables as $key => $table) {
            if ('arctype' != $table) {
                $table = $table.'_content';
            }
            try {
                schemaTable($table);
            } catch (\Exception $e) {

            }
        }
        Cache::clear();//清除数据缓存文件
        $admin_temp = glob(WWW_ROOT.'runtime/admin/temp/'.'*.php');//清除后台临时文件缓存
        array_map('unlink', $admin_temp);
        $home_temp = glob(WWW_ROOT.'runtime/home/temp/'.'*.php');//清除前台临时文件缓存
        array_map('unlink', $home_temp);
        $api_temp = glob(WWW_ROOT.'runtime/api/temp/'.'*.php');//清除API临时文件缓存
        array_map('unlink', $api_temp);
        $result = ['status' => 1, 'msg' => '清除缓存成功' ,'url'=> Request::baseFile()];
        return $result;
    }

    // 系统信息
    private function get_sys_info()
    {
        $sys_info['os']             = PHP_OS;
        $sys_info['zlib']           = function_exists('gzclose') ? 'YES' : '<font color="red">NO（请开启 php.ini 中的php-zlib扩展）</font>';   
        $sys_info['timezone']       = function_exists("date_default_timezone_get") ? date_default_timezone_get() : "no_timezone";
        $sys_info['curl']           = function_exists('curl_init') ? 'YES' : '<font color="red">NO（请开启 php.ini 中的php-curl扩展）</font>';  
        $sys_info['web_server']     = $_SERVER['SERVER_SOFTWARE'];
        $sys_info['phpv']           = phpversion();
        $sys_info['ip']             = serverIP();
        $sys_info['postsize']       = @ini_get('file_uploads') ? ini_get('post_max_size') :'unknown';
        $sys_info['fileupload']     = @ini_get('file_uploads') ? ini_get('upload_max_filesize') :'unknown';
        $sys_info['max_ex_time']    = @ini_get("max_execution_time").'s'; //脚本最大执行时间
        $sys_info['set_time_limit'] = function_exists("set_time_limit") ? true : false;
        $sys_info['domain']         = $_SERVER['HTTP_HOST'];
        $sys_info['memory_limit']   = ini_get('memory_limit');
        $mysqlinfo = Db::query("SELECT VERSION() as version");
        $sys_info['mysql_version']  = $mysqlinfo[0]['version'];
        $sys_info['curent_version']  = getCmsVersion().'-'.pcfcms_getfile(WWW_ROOT.'public/update/version.txt');
        if(function_exists("gd_info")){
            $gd = gd_info();
            $sys_info['gdinfo']     = $gd['GD Version'];
        }else {
            $sys_info['gdinfo']     = "未知";
        }
        if (extension_loaded('zip')) {
            $sys_info['zip']     = "YES";
        } else {
            $sys_info['zip']     = '<font color="red">NO（请开启 php.ini 中的php-zip扩展）</font>';
        }
        return $sys_info;
    }

}